package nacos

import (
	"fmt"
	"log"
	"oc_go/internal/g"
	"oc_go/pkg/viper"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v3"
)

func InitNacosClient() {
	// 初始化全局本地配置
	viper.InitViper()
	cc := constant.ClientConfig{
		NamespaceId:         g.OC_LOCAL_CONF.Nacos.Namespace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              g.OC_LOCAL_CONF.Nacos.LogDir,
		CacheDir:            g.OC_LOCAL_CONF.Nacos.CacheDir,
		LogLevel:            g.OC_LOCAL_CONF.Nacos.Level,
		Username:            g.OC_LOCAL_CONF.Nacos.Username,
		Password:            g.OC_LOCAL_CONF.Nacos.Password,
	}
	sc := []constant.ServerConfig{}
	for _, v := range g.OC_LOCAL_CONF.Nacos.Server {
		sc = append(sc, constant.ServerConfig{IpAddr: v.Addr, Port: uint64(v.Port)})
	}
	configClient, err := clients.NewConfigClient(vo.NacosClientParam{
		ClientConfig:  &cc,
		ServerConfigs: sc,
	})
	if err != nil {
		log.Fatal("初始化错误", err.Error())
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: g.OC_LOCAL_CONF.Nacos.DataID,
		Group:  g.OC_LOCAL_CONF.Nacos.Group,
	})
	if err != nil {
		log.Fatal("获取配置失败", err.Error())
	}
	err = yaml.Unmarshal([]byte(content), &g.OC_CONF)
	if err != nil {
		log.Fatal("解析配置错误", err.Error())
	}
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: g.OC_LOCAL_CONF.Nacos.DataID,
		Group:  g.OC_LOCAL_CONF.Nacos.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("配置文件发生了变化")
			fmt.Printf("命名空间:%s  分组:%s  dataId:%s", namespace, group, dataId)
			err := yaml.Unmarshal([]byte(data), &g.OC_CONF)
			if err != nil {
				log.Fatal("配置变化，解析错误", err.Error())
			}
		},
	})
	if err != nil {
		log.Fatal("监听配置变化失败")
	}
}
